package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.order.constant.OrderStatusEnum;
import com.atguigu.gulimall.order.constant.PayConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import static com.atguigu.gulimall.order.config.GuliMallRabbitConfig.DELAYED_ROUTING_KEY;
import static com.atguigu.gulimall.order.config.GuliMallRabbitConfig.ORDER_EVENT_EXCHANGE;
import static com.atguigu.gulimall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


/**
 * @author ShiJieLin
 */
@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor poolExecutor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        // 1.获取用户登陆信息
        ThreadLocal<MemberResponseVo> loginUser = LoginInterceptor.loginUser;
        MemberResponseVo memberResponseVo = loginUser.get();

        // 解决异步调用查看不到当前线程的请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(requestAttributes, true);

        CompletableFuture<Void> memberAddressFuture = CompletableFuture.runAsync(() -> {

            // 3.获取会员的收货地址列表 远程调用会员服务，进行查询
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            orderConfirmVo.setMemberAddressVos(address);
        }, poolExecutor).exceptionally((exception) -> {
            log.error("获取会员的收货地址远程服务调用失败", exception);
            return null;
        });

        /** 4.获取会员在购物车中选中的商品
         *  Feign调用远程接口的时候不会携带任何的请求头
         *  就会导致 调用远程的购物车接口, 会被拦截器拦截没有登陆
         *  解决方案：Feign调用的时候会加载拦截器，将请求信息重新赋予
         *  RequestInterceptor
         *  开启异步调用之后：RequestInterceptor不再同一线程就又取不到当前请求了
         */
        CompletableFuture<Void> OrderItemFuture = CompletableFuture.runAsync(() -> {

            List<OrderItemVo> items = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(items);
        }, poolExecutor).exceptionally((exception) -> {
            log.error("获取会员的购物车远程服务调用失败", exception);
            return null;
        }).thenRunAsync(() -> {
            // 1.根据购物车中的商品ID，查询是否有库存
            List<OrderItemVo> items = orderConfirmVo.getItems();
            // 2.获取购物车中商品的SkuId
            List<Long> skuIds = items.stream().map((item) -> item.getSkuId())
                    .collect(Collectors.toList());
            // 3.远程调用库存服务
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIds);
            // 4.获取库存数据
            List<SkuStockVo> stockData = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if(null != stockData && stockData.size() > 0){
                Map<Long, Boolean> map = stockData.stream().collect(Collectors
                        .toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        }, poolExecutor);

        //3、查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        // 4.设置订单的Token避免重复提交
        String token = UUID.randomUUID().toString().replace("-", "");
        // 4.1将Token保存到redis中，以便创建的订单的时候比对token是否一致
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(),
                token, 30, TimeUnit.SECONDS);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(memberAddressFuture, OrderItemFuture).get();

        return orderConfirmVo;
    }

    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        // 1.将用户提交订单数据保存，以便后续使用
        confirmVoThreadLocal.set(vo);
        // 2.创建支付订单页面所需要的数据
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 3.获取用户登录信息
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        // 4.比对用户是否重复下单
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                "return redis.call('del', KEYS[1]) else return 0 end";
        // 4.1获取用户提交的token
        String memberSubmitToken = vo.getOrderToken();
        // 4.2 使用lua脚本保证原子性：获取令牌和删除令牌，如果没有获取到则返回0
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()),
                memberSubmitToken);
        // 4.3令牌验证失败
        if(result == 0L){
            responseVo.setCode(1);
            return responseVo;
        }
        // 令牌验证成功
        // 1.创建订单 createOrder -> builderOrder -> builderOrderItems -> computePrice -> builderOrderItem
        OrderCreateTo order = createOrder();
        // 2.验证价格
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        // 误差没有超过0.01就算成功
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
            // 3.保存订单信息
            saveOrder(order);
            // 4.锁定库存，得看库存是否足够，如果不够，回滚整个订单
            WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();

            wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
            // 获取订单中每项商品的信息
            List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> {
                OrderItemVo orderItemVo = new OrderItemVo();
                orderItemVo.setSkuId(item.getSkuId());
                orderItemVo.setCount(item.getSkuQuantity());
                orderItemVo.setTitle(item.getSkuName());

                return orderItemVo;
            }).collect(Collectors.toList());
            // 封装每项商品的信息
            wareSkuLockVo.setLocks(orderItemVos);
            // 调用远程方法，进行库存上的锁定
            R lockStock = wmsFeignService.orderLockStock(wareSkuLockVo);
            // 如果锁定成功，就返回支付页面的信息
            if(null != lockStock && lockStock.getCode() == 0){
                responseVo.setCode(0);
                responseVo.setOrder(order.getOrder());
                // 将订单消息发送到MQ，然后，过指定时间之后，查看用户是否支付，如果没有，就关单
                rabbitTemplate.convertAndSend(ORDER_EVENT_EXCHANGE, DELAYED_ROUTING_KEY, order.getOrder());
                // 成功之后删除redis中的，购物车数据

                return responseVo;
            }else {
                // 库存锁定失败，进行回滚订单
                String msg = (String) lockStock.get("msg");
                throw new NoStockException(msg);
            }
        }
        responseVo.setCode(2);
        return responseVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {

        // 1.将订单信息重新查询
        OrderEntity order = baseMapper.selectOne(new QueryWrapper<OrderEntity>().
                eq("order_sn", orderEntity.getOrderSn()));
        // 2.如果订单是待付款的状态
        if(null != order && order.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){

            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(updateOrder);
            // 2.1 订单取消完成，将消息发送到 库存服务解锁队列，进行解锁
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            // 2.2订单取消之后，告知库存服务，进行对库存进行解锁
            rabbitTemplate.convertAndSend("order-event-exchange",
                    "order.release.other", orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity orderInfo = this.getOrderByOrderSn(orderSn);

        //保留两位小数点，向上取值
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        payVo.setOut_trade_no(orderInfo.getOrderSn());

        //查询订单项的数据
        List<OrderItemEntity> orderItemInfo = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());

        payVo.setSubject(orderItemEntity.getSkuName());

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        // 1.获取当前会员登陆信息
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        Long memberId = memberResponseVo.getId();
        // 2.获取当前登陆的会员订单信息
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberId)
        );
        List<OrderEntity> memberRecords = page.getRecords();
        //  3.查询会员订单中的每项商品信息
        List<OrderEntity> orderEntityList = memberRecords.stream().map((memberSn) -> {
            String orderSn = memberSn.getOrderSn();
            // 3.1获取到每项订单信息
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", orderSn));
            memberSn.setOrderItemEntityList(itemEntities);
            return memberSn;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        // 保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        // 添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        // 修改订单状态
        // 获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            // 支付成功状态
            // 获取订单号
            String orderSn = asyncVo.getOut_trade_no();
            this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        // 创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 保存订单
        this.save(orderEntity);
        // 保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuQuantity(orderTo.getNum());
        //保存商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfoData.getId());
        orderItem.setSpuName(spuInfoData.getSpuName());
        orderItem.setSpuBrand(spuInfoData.getBrandName());
        orderItem.setCategoryId(spuInfoData.getCatalogId());
        //保存订单项数据
        orderItemService.save(orderItem);
    }

    /**
     * 保存订单所有数据
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        // 获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);
        // 获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        // 批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    /** 查询用户选中的购物车信息，返回一个可支付的订单信息
     * @return
     */
    private OrderCreateTo createOrder() {

        OrderCreateTo createTo = new OrderCreateTo();
        // 1.生成订单唯一编号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = builderOrder(orderSn);
        // 2.获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn);
        // 3.验价(计算价格、积分等信息)
        computePrice(orderEntity, orderItemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);

        return createTo;
    }

    /** 构建订单的所有信息
     * @param orderSn 订单唯一编号
     * @return
     */
    private OrderEntity builderOrder(String orderSn) {
        // 1.获取用户的信息
        MemberResponseVo memberResponseVo = LoginInterceptor.loginUser.get();
        Long memberId = memberResponseVo.getId();
        String memberUsername = memberResponseVo.getUsername();
        // 2.获取用户提交订单的信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        Long addrId = submitVo.getAddrId();

        OrderEntity orderEntity = new OrderEntity();
        // 设置用户ID，用户名，创建时间，订单编号
        orderEntity.setMemberId(memberId);
        orderEntity.setMemberUsername(memberUsername);
        orderEntity.setCreateTime(new Date());
        orderEntity.setOrderSn(orderSn);

        // 远程调用仓储服务，获取用户本次订单的运费金额
        R fare = wmsFeignService.getFare(addrId);
        FareVo fareResp = fare.getData("data", new TypeReference<FareVo>() {});
        BigDecimal freight = fareResp.getFare();

        orderEntity.setFreightAmount(freight);

        // 获取到用户本次订单的收货地址信息
        MemberAddressVo address = fareResp.getAddress();

        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        // 设置订单相关的状态信息 是否付款，自动确认收货时间，确认收货状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);

        return orderEntity;
    }

    /** 构建订单中 每件商品的详细信息
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn) {

        List<OrderItemEntity> OrderItemList = new ArrayList<>();
        // 1.获取到用户购物车中选中的商品项
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();

        if(null != currentCartItems && currentCartItems.size() > 0){
            // 构建订单中的数据
            OrderItemList = currentCartItems.stream().map((item) -> {
                OrderItemEntity orderItemEntity = builderOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return OrderItemList;
    }

    /** 验算价格，优惠，运费
     * @param orderEntity 订单信息
     * @param orderItemEntities 订单中的每件商品信息
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 总价
        BigDecimal total = new BigDecimal("0.0");
        // 优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        // 积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        // 订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            // 优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            // 总价
            total = total.add(orderItem.getRealAmount());

            // 积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();
        }
        // 1.订单价格相关的
        orderEntity.setTotalAmount(total);
        // 设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        // 设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        // 设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    /** 将数据构建成 订单项中的信息
     * @param item 用户购物车中选中的商品
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo item) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1.获取商品的信息
        Long skuId = item.getSkuId();
        // 2.远程调用商品服务，获取商品的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        // 3.封装商品的SPU信息
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        // 4.商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        orderItemEntity.setSkuQuantity(item.getCount());
        // 商品的销售属性 版本信息 8+128
        String skuAttrValues = StringUtils.collectionToDelimitedString(item.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        // 5.商品的积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());

        // 6.订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        // 7.当前订单项的实际金额.总额 - 各种优惠价格
        // 原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //  原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    /**
     * 修改订单状态
     * @param orderSn
     * @param code
     */
    private void updateOrderStatus(String orderSn, Integer code,Integer payType) {

        this.baseMapper.updateOrderStatus(orderSn, code, payType);
    }
}